<template>
  <div v-loading="loading" element-loading-text="加载中">
    <el-alert title="合并规则"
      description="同一个平台下，【待发货】【未生成】【无售后】【无异常】【买家昵称、收货人姓名、手机号、收货地址一样】的订单且视为可合并订单，最多可合并10笔"
      type="warning"
      :closable="false">
    </el-alert>
    <!-- tab区 -->
    <el-tabs v-model="tabActive" @tab-click="doChangeTab">
      <template v-for="(val, key) in dict.platformType">
        <el-tab-pane v-if="key != 99" :key="key" :label="val" :name="key"> </el-tab-pane>
      </template>
    </el-tabs>

    <div class="flex">
      <div style="flex: 8;">
        <!-- 内容列表 -->
        <el-table :data="dataList" ref='table' @current-change="handleCurrentChange" :highlight-current-row="true" empty-text="暂无可合并订单" height="550">
          <el-table-column width="120px" label="可合并订单" align="center">
            <template slot-scope="scope">
              <el-tooltip placement="top" effect="light">
                <div slot="content" class="scroll-layer-box pad-r-10" style="max-height: 300px; height: auto;">
                  <div v-for="(item, index) in scope.row.externalOrderNos" :key="index" class="mar-b-5"><span>{{ item }}</span></div>
                </div>
                <el-button type="text" icon="el-icon-connection font-24 font-black"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column width="180px" label="买家昵称" prop="buyerNick" align="left">
          </el-table-column>
          <el-table-column width="300px" label="收货信息">
            <template slot-scope="scope">
              <div><span class="font-color">{{ scope.row.customerName }}</span></div>
              <div><span class="font-color">{{ scope.row.customerPhone }}</span></div>
              <div class="font-color line-2 mar-t-2" :title="scope.row.consigneeDetailAddress">{{ scope.row.consigneeDetailAddress }}</div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 统计块 -->
        <div class="mar-t-10">
          <span>符合合并规则的共</span>
          <span class="font-green font-w">{{ dataList.length }}</span>
          <span>笔收货信息</span>
        </div>
        <!-- 底部按钮区 -->
        <div slot="footer" class="dialog-footer mar-t-20 mar-b-10">
          <el-button type="primary" @click="doRefresh">刷新</el-button>
          <el-button type="primary" :disabled="!selectedRow" @click="doLinkDetail">查看详情</el-button>
          <el-button @click="doClose">关闭</el-button>
        </div>
      </div>

      <el-divider direction="vertical"></el-divider>

      <div style="flex: 3;">
        <div style="font-weight: bold;text-align: center;padding: 5px 0;">
          <el-checkbox v-if="selectedRow" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"></el-checkbox>
          <span>可合并订单</span>
          <span v-if="selectedRow" class="font-red font-w">（{{ selectedRow.externalOrderNos.length }}）</span>
        </div>
        <div class="scroll-layer-box" style="height: 520px">
          <template v-if="selectedRow">
            <el-checkbox-group v-model="mergeList" size="medium" @change="handleCheckedChange">
              <el-checkbox v-for="item in selectedRow.externalOrderNos" :label="item" :key="item"></el-checkbox>
            </el-checkbox-group>
          </template>
        </div>
        <!-- 统计块 -->
        <div class="mar-t-10">
          <span>当前已选</span>
          <span class="font-red font-w">{{ mergeList.length }}</span>
          <span>笔，默认第一笔为主订单</span>
        </div>
        <!-- 底部按钮区 -->
        <template>
          <div class="dialog-footer mar-t-20 mar-b-10">
            <el-button type="primary" :disabled="mergeList.length < 2" @click="doMerge">合并</el-button>
          </div>
        </template>
      </div>
    </div>

     <!-- 合并详情dialog -->
    <el-dialog width="1300px" v-el-drag-dialog title="合并详情" :visible.sync="mergeDetailVisible" :center="true" append-to-body>
      <merge-detail :showFlag="mergeDetailVisible" 
        :platformType="tabActive" 
        :externalOrderNos="selectedRow ? selectedRow.externalOrderNos : null" 
        @callback="doCallbackMergeDetail">
      </merge-detail>
    </el-dialog>

  </div>
</template>

<script>
  import { getDictByGroupName } from '@/api/common/common'
  import { statMergeOrder, doMergeOrder } from '@/api/goods/thirdOrder'
  import elDragDialog from '@/directive/el-dragDialog'
  import mergeDetail from './merge-detail'

  export default {
    components: { mergeDetail },
    directives: {
      elDragDialog
    },
    props: {
      showFlag: {
        type: Boolean,
        default() {
          return false
        }
      }
    },
    watch: {
      showFlag(val) {
        if (val) {
          this.refreshFlag = false
          this.doChangeTab()
        }
      },
      dataList(val) {
        if (val && val.length > 0) {
          this.$nextTick(() => this.$refs['table'].setCurrentRow(val[0]))
        }
      }
    },
    data() {
      return {
        // 数据字典
        dict: {
          platformType: {}
        },
        // tab model
        tabActive: '1',
        // 选中行
        selectedRow: null,
        // 列表
        dataList: [],
        // 合并列表
        mergeList: [],
        mergeDetailVisible: false,
        loading: false,
        isIndeterminate: false,
        refreshFlag: false,
        checkAll: false
      }
    },
    created() {
      // 获取数据字典
      getDictByGroupName('ThirdOrderDTO').then(response => {
        this.dict = response.data
      })
      this.doChangeTab()
    },
    methods: {
      // 初始化
      init() {
        const originData = this.$options.data()
        this.selectedRow = originData.selectedRow
        this.mergeList = originData.mergeList
        this.isIndeterminate = originData.isIndeterminate
        this.checkAll = originData.checkAll
      },
      // 平台切换事件
      doChangeTab() {
        this.init()
        this.loading = true
        const form = {
          enterpriseId: this.getEnterpriseId(),
          memberId: this.getMemberId(),
          platformType: this.tabActive,
          shopType: this.getMemberId() ? 1 : 2
        }
        statMergeOrder(form).then(response => {
          this.loading = false
          if (response.isError) return
          this.dataList = response.data
        })
      },
      // 刷新事件
      doRefresh() {
        this.doChangeTab()
      },
      // 查看详情事件
      doLinkDetail() {
        this.mergeDetailVisible = true
      },
      // 合并详情回调事件
      doCallbackMergeDetail(callbackFlag) {
        if (callbackFlag) {
          this.refreshFlag = true
          this.doRefresh()
        }
        this.mergeDetailVisible = false
      },
      // 取消事件
      doClose() {
        this.$emit('callback', this.refreshFlag)
      },
      // 合并事件
      doMerge() {
        this.$confirm('确认合并选中的' + this.mergeList.length + '笔订单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          const form = {
            platformType: this.tabActive,
            externalOrderNos: this.mergeList,
            mergeMainOrderNo: this.mergeList[0]
          }
          doMergeOrder(form).then(response => {
            if (response.isError) {
              this.loading = false
              return
            }
            this.refreshFlag = true
            this.$message({ message: '合并成功', type: 'success' })
            this.doRefresh()
          })
        }).catch(() => {
        })
      },
      // 全选事件
      handleCheckAllChange(val) {
        this.mergeList = val ? this.selectedRow.externalOrderNos : []
        this.isIndeterminate = false
      },
      // 勾选事件
      handleCheckedChange(value) {
        const checkedCount = value.length
        const total = this.selectedRow.externalOrderNos.length
        this.checkAll = checkedCount === total
        this.isIndeterminate = checkedCount > 0 && checkedCount < total
      },
      // 行选中事件
      handleCurrentChange(val) {
        const externalOrderNos = val.externalOrderNos
        const mergeList = externalOrderNos.length > 10 ? externalOrderNos.slice(0, 9) : externalOrderNos
        const total = externalOrderNos.length

        this.selectedRow = val
        this.mergeList = val ? mergeList : []
        this.checkAll = total === mergeList.length
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-divider {
    height: auto;
  }
</style>